//
//  SearchItemView.swift
//  XGamesLive
//
//  Created by ios on 2024/5/24.
//

import UIKit

class SearchItemView: UIView {
    
    var searchBar: MXSearchBar!
    var searchItem: UIButton!

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.createXglView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension SearchItemView{
    @objc private func searchItemAction(){
        self.searchBar.isHidden = false
        self.searchBar.becomeFirstResponder()
        UIView.animate(withDuration: 0.25) {
            self.searchBar.alpha = 1
            self.searchItem.alpha = 0
            self.snp.updateConstraints { make in
                make.width.equalTo(conversionWithScrennWidth(value: 300.0))
            }
        } completion: { _ in
            self.searchItem.isHidden = true
        }
    }
}

extension SearchItemView{
    func pickupSearchBar(){
        self.searchBar.resignFirstResponder()
        UIView.animate(withDuration: 0.25) {
            self.searchBar.isHidden = true
            self.searchItem.isHidden = false
            self.searchBar.alpha = 0
            self.searchItem.alpha = 1
            self.snp.updateConstraints { make in
                make.width.equalTo(conversionWithScrennWidth(value: 40.0))
            }
        }
    }
}



extension SearchItemView{
    private func createXglView(){
        self.searchBar = MXSearchBar().then({ make in
            make.placeholder = "Enter key word"
            make.showsCancelButton = true
            make.backColor = UIColor.hexColor("#001310").withAlphaComponent(0.5)
            make.searchBarStyle = UISearchBar.Style.minimal
            make.backgroundColor = UIColor.hexColor("#001310").withAlphaComponent(0.5)
            make.barTintColor = UIColor.white
            make.contentInset = UIEdgeInsets.init(top: 1, left: 0, bottom:1, right: 0)
            make.layerCornerRadius = 16.0
            make.setImage(imageWithName("icon_xgl_search_white"), for: .search, state: .normal)
            make.alpha = 0
            make.setImage(imageWithName(""), for: .clear, state: .normal)
        })
        self.searchItem = UIButton().then({ make in
            make.setImage(imageWithName("icon_xgl_search_white"), for: .normal)
            make.addTarget(self, action: #selector(self.searchItemAction), for: .touchUpInside)
        })
        self.addSubviews([searchBar,searchItem])
        self.searchBar.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.height.equalTo(32.0)
            make.width.equalToSuperview()
            make.right.equalToSuperview()
        }
        searchItem.snp.makeConstraints { make in
            make.centerY.right.equalToSuperview()
            make.width.height.equalTo(40.0)
        }
    }
}
